/**
 * @author lixiaoshuang@zbj.com
 * @date 2017-01-17
 * @desc  公共函数库
 */

let util = {
    // 补0方法
    formatNumber(n){
        n = n.toString();
        return n[1] ? n : '0' + n;
    },
    // 格式化时间
    formatTime(date){
        return [
            date.getFullYear(),
            date.getMonth() + 1,
            date.getDate(),
            date.getHours(),
            date.getMinutes(),
            date.getSeconds()
        ].map(this.formatNumber).join('');
    },

    // 获取qq音乐排行榜请求地址
    // topId 为榜单类型
    getPhUrl(topId){
        let param = 'showapi_appid=30126&showapi_timestamp=' +
            this.formatTime(new Date()) + '&topid=' + topId + '&showapi_sign=04e8714b21954f54b77af9cbc9b2670a';
        return 'https://route.showapi.com/213-4?' + param;
    },

    // 获取排行榜数据
    getPhData(data, cb){
        let url = this.getPhUrl(data.topId);
        this.ajax(url, cb);
    },

    // 异步请求
    ajax(url, cb){
        wx.request({
            url,
            success: (res)=>{
                let result = res.data || {},
                    err = null,
                    data = null;
                result.showapi_res_code != 0 ? 
                    err = {
                        code: result.showapi_res_code,
                        msg: result.showapi_res_error
                    } :
                    data = result.showapi_res_body.pagebean;
                cb && cb(err,data);
            }
        });
    },

    // 提示框
    alert(content, cb, btnText){
        wx.showModal({
            title: '系统提示',
            content,
            confirmText: btnText,
            showCancel: false,
            success: function(res) {
                if (res.confirm) {
                    cb && cb();
                }
            }
        });
    }
};

module.exports = util;
